package com.luyu.Exception;

import cn.hutool.core.collection.CollUtil;
import com.luyu.resp.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Author lyh
 */
@RestControllerAdvice(basePackages = {"com.luyu"})
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<?> validationBodyException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        List<ObjectError> globalErrors = bindingResult.getGlobalErrors();
        List<String> fieldErrorList = fieldErrors.stream().map(FieldError::getDefaultMessage)
                .toList();
        List<String> globalList = globalErrors.stream().map(ObjectError::getDefaultMessage)
                .toList();
        String msg = CollUtil.join(CollUtil.union(fieldErrorList, globalList), ";");
        return ResponseResult.ERROR("400", "400", msg);
    }

}
